# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

library(gplots)
library(optparse)
library(ropls)
library(magrittr)
library(ComplexHeatmap)
library(tidyverse)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

diffData <- read_csv("../../potential/Markers.csv")

if (nrow(diffData) == 0) {
    quit(status = 0)
}

diffNames <- diffData %>%
.$Metabolite

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

classNotes <- sampleInfo %>%
.$ClassNote %>%
unique()

selfCorTest = function(da1, method="spearman"){
    name1 <- colnames(da1)
    tr_da1 <- as.matrix(da1)
    num1 <- ncol(da1)
    pvalue <- vector()
    value <- vector()
    id1 <- vector()
    id2 <- vector()
    rec <- 1
    for (i in 1 : num1) {
        for (j in 1 : num1) {
            a1 <- tr_da1[, i]
            a2 <- tr_da1[, j]
            id1[rec] <- name1[i]
            id2[rec] <- name1[j]
            a1 <- as.numeric(a1)
            a2 <- as.numeric(a2)
            corr <- cor.test(a1, a2, method = method)
            esti <- as.matrix(corr$estimate)[1]
            value[rec] <- esti
            pvalue[rec] <- corr$p.value
            rec <- rec + 1
        }
    }
    list(node1 = id1, node2 = id2, cor = value, p = pvalue)
}


groupNames <- c(classNotes, paste0(classNotes, collapse = "_vs_"))

superClassData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
select(c("Metabolite", "Class"))

orignalData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    filter(Metabolite %in% diffNames) %>%
    as.data.frame()

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
    set_colnames(c("arg", "value")) %>%
    column_to_rownames("arg")

corP <- configData["cor.p", "value"] %>%
as.numeric()
corFdr <- configData["cor.fdr", "value"] %>%
as.numeric()
cor <- configData["cor.coe", "value"] %>%
as.numeric()

print(groupNames)

for (groupName in groupNames) {
    groups <- unlist(strsplit(groupName, "_vs_"))
    sampleIds <- sampleInfo %>%
        filter(ClassNote %in% groups) %>%
        .$SampleID
    data <- orignalData %>%
        select(c("Metabolite", sampleIds)) %>%
        column_to_rownames("Metabolite") %>%
        as.data.frame()

    data <- t(data)

    method <- "spearman"
    parent <- str_replace_all(groupName, "_vs_", "_and_")
    createWhenNoExist(parent)
    inData <- data %>%
    as.matrix()

    listRs <- selfCorTest(inData)

    allData <- data.frame(Node1 = listRs$node1, Node2 = listRs$node2, r = listRs$cor, P = listRs$p,
    stringsAsFactors = F) %>%
        mutate_at(vars(c("r")), function(x){
            ifelse(is.na(x), 0, x)
        }) %>%
        mutate_at(vars(c("P")), function(x){
            ifelse(is.na(x), 1, x)
        }) %>%
        mutate(FDR = p.adjust(P, method = "fdr"))

    corData <- allData %>%
        select(c("Node1", "Node2", "r")) %>%
        spread(Node1, "r") %>%
        rename(` ` = Node2)

    write_csv(corData, paste0(parent, "/Intra_r_Matrix.csv"))

    pData <- allData %>%
        select(c("Node1", "Node2", "P")) %>%
        spread(Node1, "P") %>%
        rename(` ` = Node2)

    write_csv(pData, paste0(parent, "/Intra_P_Matrix.csv"))

    fdrData <- allData %>%
        select(c("Node1", "Node2", "FDR")) %>%
        spread(Node1, "FDR") %>%
        rename(` ` = Node2)

    write_csv(fdrData, paste0(parent, "/Intra_FDR_Matrix.csv"))

    edgeData <- allData %>%
        filter(P < corP & FDR <= corFdr & abs(r) > cor) %>%
        filter(Node1 != Node2) %>%
        mutate(distName = {
            Node1 %>%
            map2_chr(Node2, function(x, y){
                vec <- c(x, y) %>%
                sort()
                str_c(vec, collapse = ";")
            })
        }) %>%
        distinct(distName, .keep_all = T) %>%
        select(- c("distName")) %>%
        arrange(desc(abs(r)))

    write_csv(edgeData, paste0(parent, "/Network_Edges_for_Cytoscape.csv"))

    nodes <- unique(c(edgeData$Node1, edgeData$Node2))
    infoData <- tibble(Node = nodes) %>%
        mutate(Size = {
            Node %>%
            map_int(function(x){
                edgeData %>%
                    filter(Node1 == x | Node2 == x) %>%
                    nrow()
            })
        }) %>%
        left_join(superClassData, by = c("Node" = "Metabolite")) %>%
        rename(Type = Class) %>%
        mutate_at(vars("Type"), function(x){
            replace_na(x, "Others")
        })
    print(infoData)
    write_csv(infoData, paste0(parent, "/Network_Nodes_for_Cytoscape.csv"))
}



